use std::env;
use std::path::PathBuf;

fn main() {
     // 1. 检测目标平台
     let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
     let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
     
     // 2. 构建库路径
     let lib_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
         .join("lib")
         .join(format!("{}_{}", target_os, target_arch));
     
     // 3. 验证库是否存在
     if !lib_dir.exists() {
         panic!("SQLite library not found for target: {}_{}", target_os, target_arch);
     }
     
     // 4. 设置链接参数
     println!("cargo:rustc-link-search={}", lib_dir.display());
     
     // 5. 根据平台设置链接库名称
     match target_os.as_str() {
         "windows" => {
             println!("cargo:rustc-link-lib=static=sqlite3");
             
             // ========== 添加 DLL 复制逻辑 ==========
             let dll_src = lib_dir.join("sqlite3.dll");

             if dll_src.exists() {
                 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());

                 // 输出目录结构: target/debug/build/<project>-<hash>/out
                 // 需要向上三级才能到可执行文件目录

                 let target_dir = out_dir
                     .parent().unwrap()  // build/<project>-<hash>
                     .parent().unwrap()  // build
                     .parent().unwrap(); // target/debug 或 target/release
                 
                 let dll_dest = target_dir.join("sqlite3.dll");
                 
                 if let Err(e) = std::fs::copy(&dll_src, &dll_dest) {
                     eprintln!("Failed to copy DLL: {}", e);
                 } else {
                     println!("Copied SQLite DLL to: {}", dll_dest.display());
                     
                     // 在 release 模式下也复制到 release 目录
                     if let Ok(profile) = env::var("PROFILE") {
                         if profile == "release" {
                             let release_dir = target_dir
                                 .parent().unwrap() // target
                                 .join("release");
                             
                             if let Err(e) = std::fs::copy(&dll_src, release_dir.join("sqlite3.dll")) {
                                 eprintln!("Failed to copy DLL to release dir: {}", e);
                             }
                         }
                     }
                 }
             }
         }
         _ => println!("cargo:rustc-link-lib=static=sqlite3"),
     };
     
     // 6. 添加平台特定的依赖库
     if target_os == "linux" {
         println!("cargo:rustc-link-lib=dylib=dl");
         println!("cargo:rustc-link-lib=dylib=pthread");
     }
     
     // 7. 重新运行条件（当库文件变化时）
     println!("cargo:rerun-if-changed={}", lib_dir.display());
}